# import jusmargui
from PySide2.QtWidgets import (
    QApplication,
    QWidget,
    QTableWidgetItem,
    QTableWidget,
    QHeaderView,
    QAbstractItemView,
    QVBoxLayout,
    QTabWidget,
    QGroupBox,
    QLabel,
    QLineEdit,
    QHBoxLayout,
    QGridLayout,
    QComboBox,
    QPushButton,
    QListWidget,
    QDialog,
    QButtonGroup,
    QRadioButton,
    QCheckBox,
    QListWidgetItem,
    QMessageBox,
    QSizePolicy,
    QSpacerItem,
)
from PySide2.QtCore import Qt, Signal
from PySide2.QtGui import QPixmap, QDoubleValidator, QIntValidator, QImage, QMouseEvent
import sys
import csv
import os
import json
import subprocess
import copy
from gui.controls import envs
from datetime import datetime
from .. import message_box as MBox
from .. import config as Config
from ..utils import Utils
from ..dlg_model_params import DlgModeResetCls
from ..custom_widget import LineEditFloat, LineEditStr, SelectBox
from ..beam_and_mass_point.tank_select_node import DlgTankSelectNode


class ClickableLineEdit(QLineEdit):
    def __init__(self, text="", onClicked=None):
        super().__init__(text)
        self.setReadOnly(True)
        self.onClickedEvent = onClicked

    def getValue(self):
        return self._get()

    def setValue(self, value: int = None):
        self._set(value)

    def _get(self):
        value = self.text()
        if value != "":
            try:
                return int(value)
            except ValueError:
                print("输入的不是一个数字字符串")
        return None

    def _set(self, value: int = None):
        if value is None:
            value = ""
        self.setText(str(value))

    def mousePressEvent(self, event: QMouseEvent):
        # 捕获鼠标点击事件
        if event.button() == Qt.LeftButton:  # 检查是否是左键点击
            if self.onClickedEvent:
                self.onClickedEvent()
        super().mousePressEvent(event)  # 调用父类的 mousePressEvent 方法


class DlgAddTank(DlgModeResetCls):
    ok_signal = Signal(str, int, dict)

    def __init__(self, parent=None, params={}):
        super().__init__(parent)
        self.widgetDict = {}
        layout = QVBoxLayout()
        self.type = params.get("type") or "add"
        self.index = params.get("index")
        self.data = params.get("data") or []
        self.names = params.get("names") or []
        self.mainData = params.get("grid") or []
        self.setWindowTitle("创建贮箱" if self.type == "add" else "修改贮箱")

        self.paramsList = [
            {"name": "name", "type": "str", "title": "名称"},
            {
                "name": "startId",
                "type": "clickEdit",
                "title": "起始id",
                "onClicked": lambda *args, **kwargs: self.startIdClick(*args, **kwargs),
            },
            {
                "name": "endId",
                "type": "clickEdit",
                "title": "终止id",
                "onClicked": lambda *args, **kwargs: self.endIdClick(*args, **kwargs),
            },
        ]

        gridLayout = QGridLayout()
        layout.addLayout(gridLayout)
        self.createParameterUI(self.paramsList, gridLayout)

        btnLayout = QHBoxLayout()
        btnLayout.setContentsMargins(-1, 10, -1, -1)
        cancelBtn = QPushButton("取消")
        okBtn = QPushButton("确定")

        btnLayout.setAlignment(Qt.AlignCenter)
        btnLayout.addWidget(okBtn)
        btnLayout.addWidget(cancelBtn)
        layout.addLayout(btnLayout)

        okBtn.clicked.connect(self.on_okBtn_clicked)
        cancelBtn.clicked.connect(self.close)

        self.setLayout(layout)

        if self.type == "edit":
            self.updateUI(data=self.data)

    def updateUI(self, data):
        if data:
            self.widgetDict["name"].setValue(data.get("name"))
            site_point = data.get("site_point") or [None, None]
            # ids 数量如果小于2 则填充None
            ids_length = len(site_point)
            if ids_length < 2:
                site_point.extend([None] * (2 - ids_length))
            self.widgetDict["startId"].setValue(site_point[0])
            self.widgetDict["endId"].setValue(site_point[-1])

    def on_okBtn_clicked(self):
        dict = {}
        for key, widget in self.widgetDict.items():
            value = widget.getValue()
            if value is None:
                MBox.warning("请填写完整信息！")
                return
            dict[key] = value
        if dict["name"] in self.names:
            MBox.warning("贮箱名称已存在！")
            return
        startId = dict["startId"]
        endId = dict["endId"]
        if startId > endId:
            MBox.warning("起始id不能大于终止id！")
            return
        totalIds = [
            row[0] for row in self.mainData if Utils.toIntOrNone(row[0]) != None
        ]
        # 过滤并排序
        site_point = sorted([x for x in totalIds if startId <= x <= endId])
        dict["site_point"] = site_point
        del dict["startId"]
        del dict["endId"]
        self.close()
        self.ok_signal.emit(self.type, self.index, dict)

    def startIdClick(self, *args, **kwargs):
        dlgTankSelectNode = DlgTankSelectNode.show(
            parent=self, params={"data": self.mainData}
        )
        dlgTankSelectNode.ok_signal.connect(self.on_update_startId)

    def endIdClick(self, *args, **kwargs):
        dlgTankSelectNode = DlgTankSelectNode.show(
            parent=self, params={"data": self.mainData}
        )
        dlgTankSelectNode.ok_signal.connect(self.on_update_endId)

    def on_update_startId(self, node):
        self.widgetDict["startId"].setValue(node)

    def on_update_endId(self, node):
        self.widgetDict["endId"].setValue(node)

    def createParameterUI(self, list, layout, row=0, col=0):
        for index, item in enumerate(list):
            name = item.get("name")
            index = row + index
            label = QLabel(item["title"])
            layout.addWidget(label, index, 0 + col)
            if item["type"] == "str":
                self.widgetDict[name] = LineEditStr()
            elif item["type"] == "float":
                self.widgetDict[name] = LineEditFloat()
            elif item["type"] == "clickEdit":
                self.widgetDict[name] = ClickableLineEdit(
                    onClicked=item.get("onClicked")
                )
            layout.addWidget(self.widgetDict[name], index, 1 + col)
